package com.woniu.cinema.controller;

import java.util.List;

import com.woniu.cinema.dto.DynamicMovieRequest;
import com.woniu.cinema.vo.MovieVo;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import com.woniu.common.annotation.Log;
import com.woniu.common.core.controller.BaseController;
import com.woniu.common.core.domain.AjaxResult;
import com.woniu.common.enums.BusinessType;
import com.woniu.cinema.domain.Movie;
import com.woniu.cinema.service.MovieService;
import com.woniu.common.utils.poi.ExcelUtil;
import com.woniu.common.core.page.TableDataInfo;

import javax.servlet.http.HttpServletRequest;

/**
 * 影片信息Controller
 *
 * @author yy
 * @date 2023-09-27
 */
@RestController
@RequestMapping("/cinema/movie")
public class MovieController extends BaseController
{
    @Autowired
    private MovieService movieService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RedissonClient redissonClient;



    /**
     * 查询影片信息列表
     */
    @GetMapping("/list")
    public TableDataInfo list(Movie movie)
    {
        startPage();
        List<Movie> list = movieService.selectMovieList(movie);
        return getDataTable(list);
    }

    @GetMapping("dynamic/list")
    public TableDataInfo dynamiclist(DynamicMovieRequest request)
    {

        startPage();
        List<Movie> list = movieService.dynamiclist(request);
        return getDataTable(list);
    }

//    keys *
    //portal主页访问
    @GetMapping("web/list")
    public TableDataInfo weblist(Movie movie, HttpServletRequest request)
    {
        String pageNum = request.getParameter("pageNum");
        String pageSize = request.getParameter("pageSize");
        String movieStatus = request.getParameter("movieStatus");
        String orderByColumn = request.getParameter("orderByColumn");
        String isAsc = request.getParameter("isAsc");

        String redisKey = "potal_index_"+pageNum+"_"+pageSize+"_"+movieStatus+"_"+orderByColumn+"_"+isAsc;


        //1、查询redis缓存，如果命中，直接返回
        List<Movie> cachedList = (List<Movie>)redisTemplate.opsForList().range(redisKey, 0, -1);
        if(cachedList.size()>0){
            return getDataTable(cachedList);
        }

        String lockKey = "index_cache_lock";
        RLock lock = redissonClient.getLock(lockKey);

        try{
//         加锁 //Redisson --redis官方推荐的客户端工具
            //有个看门狗，watchdog(就是个定时任务)，监控锁中的代码是否执行完毕
            //每隔10秒钟，就检查一下锁是否释放了，如果没有，就把锁的超时时间恢复成30秒
//            内部使用LUA脚本实现
            lock.lock();

            //第二次在查询redis，如果命中，直接返回
            cachedList = (List<Movie>)redisTemplate.opsForList().range(redisKey, 0, -1);
            if(cachedList.size()>0){
                return getDataTable(cachedList);
            }

            if(cachedList==null || cachedList.size()==0){

                System.out.println("需要查询数据库。。。");
                //查询数据库
                startPage();
                cachedList = movieService.selectMovieList(movie);
                //把结果放入redis中
                redisTemplate.opsForList().rightPushAll(redisKey, cachedList);
            }
        }finally {
            //解锁
            lock.unlock();
        }


        return getDataTable(cachedList);
    }

    /**
     * 导出影片信息列表
     */
    @Log(title = "影片信息", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(Movie movie)
    {
        List<Movie> list = movieService.selectMovieList(movie);
        ExcelUtil<Movie> util = new ExcelUtil<Movie>(Movie.class);
        return util.exportExcel(list, "movie");
    }

    /**
     * 获取影片信息详细信息
     */
    @GetMapping(value = "/{movieId}")
    public AjaxResult getInfo(@PathVariable("movieId") Integer movieId)
    {
        return AjaxResult.success(movieService.selectMovieById(movieId));
    }


    @GetMapping(value = "web/queryMovieByMovieId")
    public AjaxResult queryMovieByMovieId(Integer movieId)
    {
        MovieVo movieVo = movieService.queryMovieByMovieId(movieId);
        return AjaxResult.success(movieVo);
    }

    @RequestMapping(value = "feign/queryMovieVoByMovieId")
    public List<MovieVo> queryMovieVoByMovieIdMovieId(@RequestParam("movieId") Integer movieId)
    {
        List<MovieVo> list = movieService.queryMovieVoByMovieIdMovieId(movieId);
        return list;
    }
    /**
     * 新增影片信息
     */
    @Log(title = "影片信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Movie movie)
    {
        return toAjax(movieService.insertMovie(movie));
    }

    /**
     * 修改影片信息
     */
    @Log(title = "影片信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Movie movie)
    {
        int i = movieService.updateMovie(movie);

        //更新数据库之后，把缓存中对应的值删除
        redisTemplate.delete("potal_index_*");
        return toAjax(i);
    }

    /**
     * 删除影片信息
     */
    @Log(title = "影片信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{movieIds}")
    public AjaxResult remove(@PathVariable Integer[] movieIds)
    {
        return toAjax(movieService.deleteMovieByIds(movieIds));
    }
}
